package com.xemotion.weceem.controllers

import org.weceem.content.WcmSpace

import org.codehaus.groovy.grails.web.context.ServletContextHolder
import grails.converters.JSON

/**
 * ClusterController
 * @author notex
 *
 * Receive message from cluster manager with JSON-RPC.
 */
class ClusterController {
	
    static allowedMethods = [index: "POST"]
	
    def wcmContentRepositoryService

    def index = {
        def json_params = request.JSON
		
        if (!json_params.method) { sendBadRequest(); return; }
		
        switch (json_params.method) {
            case "addFile":
            if (!json_params.path && !json_params.data) { sendBadRequest(); return; }
            addFile(json_params.path, json_params.data)
            break;
            case "invalidateCaching":
            if (!json_params.path) { sendBadRequest(); return; }
            invalidateCaching(json_params.path)
            break;
            case "removeFile":
            if (!json_params.path) { sendBadRequest(); return; }
            removeFile(json_params.path)
            break;
            default:
            render "ClusterController is connected."
            break;
        }
    }
	
    private void addFile(resource_path, data) {
        log.debug "resource_path: " + resource_path

        // This not work with transaction.
//        def file_bin = WcmContentFileBin.findByResourcePath(resource_path)
//        if (!file_bin) {
//            log.error "ContentFileBin not found with path: " + resource_path
//            response.status = 404
//            def json_resp = [ error: [message: "ContentFileBin not found with path: " + resource_path],
//                path: resource_path]
//            render json_resp as JSON
//            return
//        }
		
        def data_bin = data.decodeBase64()
        def file = new File( ServletContextHolder.servletContext.getRealPath( resource_path ) )
        if (!file.parentFile.exists()) {
            assert file.parentFile.mkdirs()
            log.debug "mkdir ${file.parent}"
        }
        if (file) {
            file << data_bin
        } else {
            new File( ServletContextHolder.servletContext.getRealPath(resource_path) ).mkdirs()
        }
			
        log.debug "${resource_path} is saved."
        response.status = 201
        def json_resp = [ result: 1, error: null, resourcePath: resource_path,
            message: "${resource_path} is created."]
        render json_resp as JSON
    }
	
    private void invalidateCaching(cache_path) {
        log.debug "cache_path: " + cache_path
        def path_array = cache_path.split('/')
        def space_uri = path_array[0]
        def content_uri = path_array[1 .. path_array.size()-1].join('/')
		
        def space = WcmSpace.findByAliasURI(space_uri)
        wcmContentRepositoryService.invalidateCachingForURI(space, content_uri)
        response.status = 201
        def json_resp = [ result: 1, error: null, message: "Invalidated cache path: ${cache_path}"]
        render json_resp as JSON
    }
	
    private void removeFile(resource_path) {
        log.debug "resource_path: " + resource_path
		
        def file = new File( ServletContextHolder.servletContext.getRealPath( resource_path ) )
        if (!file) {
            log.error "File not found with path: " + path
            response.status = 404
            def json_resp = [ error: [message: "File not found with path: " + path],
                path: path]
            render json_resp as JSON
        }
        file.delete()
        response.status = 200
        def json_resp = [ result: 1, error: null, resourcePath: resource_path,
            message: "${resource_path} is deleted."]
        render json_resp as JSON
    }
	
    private def sendBadRequest() {
        response.status = 400
        def json_resp = [ error: [message: "Bad request."]]
        render json_resp as JSON
    }
	
}
